﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
using System.Xml;

namespace Raona.Silverlight
{
    public class AppSettings
    {
        public string Key
        {
            get;
            set;
        }

        public string Value
        {
            get;
            set;
        }
    }


    public class ConfigurationManager
    {

        #region Properties

        private static Dictionary<string, string> _appSettings;

        public static event EventHandler<EventArgs> ConfigurationAvailable;

        public static Dictionary<string,string> AppSettings
        {
            get
            {
                return _appSettings;
            }
        
        }

        #endregion

        public static void LoadConfig()
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri("Config.xml", UriKind.Relative));
        }

        public static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {

            if (e.Error != null)
            {
                throw e.Error;
            }

            // load the data
            XDocument config = XDocument.Parse(e.Result);

            var appsettings = from x in config.Descendants("AppSettings").Descendants("Add")
                              select new AppSettings { Key = (string)x.Attribute("Key"), Value = x.Attribute("Value").Value };

            _appSettings = new Dictionary<string,string>();

            // add to collection
            if (appsettings.Count() > 0)
            {
                foreach (AppSettings y in appsettings)
                {
                    _appSettings[y.Key] = y.Value;
                }
            }

            // notify that its available
            if (ConfigurationAvailable != null)
                ConfigurationAvailable(null, new EventArgs());
        }

    }
}
